<?php

	/**
	 * @package		CoreProject
	 * @subpackage	Parser
	 *
	 * @example
	 *		../examples/template.php
	 *
	 * cpr_Parser_Template
	 *
	 */

	class cpr_Parser_Template
	{
		/**
		 * @var	string
		 */
		private $_context = '';
		
		/**
		 * @var array
		 */
		private $_data = array();
		
		/**
		 * @param	string	$fileName
		 * @return	cpr_Parser_Template
		 */
		public function cpr_Parser_Template($_fileName = null)
		{
			if (null !== $_fileName)
			{
				$this->SetTemplateAsFile($_fileName);
			}
		}
		
		/**
		 * @param	string	$_text
		 */
		public function SetTemplateAsText($_text)
		{
			$this->_context = $_text;
		}

		/**
		 * @param	string	$_fileName
		 * @return	bool
		 */
		public function SetTemplateAsFile($_fileName)
		{
			if (file_exists($_fileName))
			{
				$this->_context = @file_get_contents($_fileName);
				return (false !== $this->_context);
			}
			
			return false;
		}
		
		/**
		 * @param	string	$_key
		 * @param	mixed	$_value
		 */
		public function SetContext($_key, $_value)
		{
			$this->_data[$_key] = $_value;
		}
		
		/**
		 * @return	string
		 */
		public function Write()
		{
			return $this->_parseData($this->_context, $this->_data);
		}
		
		public function Clear()
		{
			$this->_data = array();
		}
		
		/**
		 * @param	string	$_context
		 * @param	array	$_data
		 * @return	string
		 */
		private function _parseData($_context, $_data)
		{
			foreach ($_data as $_key => $_value)
			{
				if (is_array($_value))
				{
					$_start = strpos($_context, '{#FOR|'.$_key);
					$_startEnd = strpos($_context, '#}', $_start);
					$_end = strpos($_context, '{#END#}', $_startEnd);
					if (false === $_start || false === $_startEnd || false === $_end)
					{
						break;
					}
					
					$_out = '';
					$_repstr = substr($_context, $_startEnd + 2, $_end - $_startEnd - 2);
					
					foreach ($_value as $_item)
					{
						$_tmp = $_repstr;
						if (is_array($_item))
						{
							foreach ($_item as $_k => $_v)
							{
								$_tmp = str_replace('{#'.$_key.'>'.$_k.'#}', (string) $_v, $_tmp);
							}
						}
						$_out .= $_tmp;
					}
					
					$_context = str_replace('{#FOR|'.$_key.'#}'.$_repstr.'{#END#}', $_out, $_context);
					
				}
				else
				{
					$_context = str_replace('{#'.$_key.'#}', (string) $_value, $_context);
				}
			}
			
			return $_context;
		}
	}